package com.jiuzhe.commercial.ui.house;

import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.adapter.CityLeftAdapter;
import com.jiuzhe.commercial.adapter.CityRightAdapter;
import com.jiuzhe.commercial.adapter.FriendsAdapter;
import com.jiuzhe.commercial.base.BaseActivity;
import com.jiuzhe.commercial.base.Friend;
import com.jiuzhe.commercial.bean.CityBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.utils.CharacterParser;
import com.jiuzhe.commercial.utils.PinyinComparator;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;
import com.jiuzhe.commercial.view.MyLetterView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * Created by huanghao on 2018/6/4.
 */

public class CityListSelectActivity2 extends BaseActivity {

    @BindView(R.id.list_friends)
    ListView list_friends;
    @BindView(R.id.tv_dialog)
    TextView tv_dialog;
    @BindView(R.id.right_letter)
    MyLetterView right_letter;
    @BindView(R.id.layout_list)
    RelativeLayout layoutList;

    private CityLeftAdapter cityLeftAdapter;
    private RecyclerView mRvRight;
    private CityRightAdapter cityRigthAdapter;
    private AlertDialog alertDialog;
    private String id;


    private List<Friend> friends;
    private List<CityBean> list = new ArrayList<>();
    private List<String> list1 = new ArrayList<>();
    private List<CityBean> list2 = new ArrayList<>();

    /**
     * 根据拼音来排列ListView中的数据
     */
    private PinyinComparator pinyinComparator;

    private CharacterParser characterParser;
    private String mCity;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_citys_select);
        setTitle("选择目的地");
    }

    private void initData() {
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
       // String[] names = getResources().getStringArray(R.array.names);
        friends = new ArrayList<Friend>();
        if (list != null && list.size() > 0)
        for (int i = 0; i < list.size(); i++) {
            Friend f = new Friend();
            f.setName(list.get(i).getCityName());
            f.setId(list.get(i).getId());
            f.setAreaList(list.get(i).getAreaList());
            String pinyin = characterParser.getSelling(list.get(i).getCityName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                f.setSortLetters(sortString.toUpperCase());
            } else {
                f.setSortLetters("#");
            }
            friends.add(f);
        }
        Collections.sort(friends, pinyinComparator);
        initView2();
    }

    /**
     * 得到市
     */
    public void initView2() {
        right_letter.setTextDialog(tv_dialog);
        final FriendsAdapter adapter = new FriendsAdapter(this, friends);
        right_letter.setOnTouchingLetterChangedListener(new MyLetterView.OnTouchingLetterChangedListener() {
                    @Override
                    public void onTouchingLetterChanged(String s) {
                        // 该字母首次出现的位置
                        int position = adapter.getPositionForSection(s.charAt(0));
                        if (position != -1) {
                            list_friends.setSelection(position);
                        }
                    }
                });
        list_friends.setAdapter(adapter);
        list_friends.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showDlog(position);
            }
        });
    }


    @Override
    protected void loadData() {
        dialog.show();
        HashMap<String, String> map = new HashMap<>();
        String token = SPUtil.getString(CityListSelectActivity2.this, Constants.TOKEN);
        id = SPUtil.getString(this, Constants.ID);
        String autoSignStr = Constants.CITY.substring(Constants.CITY.lastIndexOf("0/")+1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        String url = Constants.CITY  + "?token=" + id + "&sign=" + signStr;
        HttpClient.get(this, url , map, new CallBack<List<CityBean>>() {
            @Override
            public void onSuccess(List<CityBean> result) {
                dialog.dismiss();
                list.clear();
                list.addAll(result);
                initData();
            }

            @Override
            public void onFailure(int errorType, String message) {
                super.onFailure(errorType, message);
                dialog.dismiss();
            }
        });
    }

    /**
     * 得到商圈
     * @param
     */
    private void showDlog(final int position) {
        alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_city);
        window.setGravity(Gravity.CENTER);
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = this.getResources().getDisplayMetrics().widthPixels/5*5;
        lp.height = this.getResources().getDisplayMetrics().heightPixels/5*3;
        window.setAttributes(lp);
        RecyclerView rv_left = (RecyclerView) alertDialog.findViewById(R.id.rv_left);
        mRvRight = alertDialog.findViewById(R.id.rv_right);
        rv_left.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        rv_left.setItemAnimator(new DefaultItemAnimator());
        cityLeftAdapter = new CityLeftAdapter(list1);
        mCity = friends.get(position).getName();
        final List<String> areaList =  friends.get(position).getAreaList();
        rv_left.setAdapter(cityLeftAdapter);
                list1.clear();
                list1.addAll(friends.get(position).getAreaList());
                cityLeftAdapter.notifyDataSetChanged();

        cityLeftAdapter.setOnItemClickListener(new CityLeftAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("area", areaList.get(position));
                intent.putExtra("city", mCity);
                setResult(3, intent);
                finish();
            }
        });
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (alertDialog != null)
            alertDialog.dismiss();
        alertDialog = null;
    }
}
